<script setup>
import {ref} from 'vue'
import {message} from 'ant-design-vue'
import http from '@/config/axios-config'
import {useUserStore} from '@/stores/user'
import {useRoute, useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

let form = ref({})
let loading = ref(false)

const goHome = () => {
  const query = route.query
  const path = query && query.from ? query.from : '/'
  router.push({path: path})
}

const onFinishHandler = (values) => {
  loading.value = true
  http.post('/account/password', values).then(res => {
    if (res.code === 200) {
      userStore.setUserToken(res.result.Token)
      message.success('登录成功')
      setTimeout(() => {
        goHome()
      }, 800)
    } else {
      message.error(res.msg || '登录失败')
    }
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}
</script>

<template>
  <div class="login-wrapper">
    <div class="login-form">
      <h4>用户登录</h4>
      <a-form
          :model="form"
          autocomplete="off"
          @finish="onFinishHandler"
      >
        <a-form-item
            required
            name="UserName"
            :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="form.UserName" size="large">
            <template #prefix>
              <my-icon type="icon-user"/>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item
            required
            name="Password"
            :rules="[{ required: true, message: '请输入登录密码' }]"
        >
          <a-input-password v-model:value="form.Password" size="large">
            <template #prefix>
              <my-icon type="icon-lock"/>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" block :loading="loading">
            {{ loading ? '登录中...' : '登 录' }}
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
.login-wrapper {
  padding: 50px 20px;
  position: relative;
  box-sizing: border-box;
  background-image: url("@/assets/img/bg-login.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  min-height: 100vh;

  &:before {
    content: "";
    background-color: rgba(0, 0, 0, .2);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .login-form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%);
    margin-top: -220px;

    width: 360px;
    max-width: 100%;
    padding: 25px 30px;
    box-shadow: 0 3px 6px rgb(0 0 0 / 15%);
    box-sizing: border-box;
    border-radius: 4px;
    z-index: 2;
    background: #fff;

    h4 {
      font-size: 20px;
      text-align: center;
      margin-bottom: 25px;
    }
  }
}
</style>
